<template>
  <el-form ref="passwordForm" :model="form" size="small" label-width="90px" :rules="rules">
    <el-form-item label="旧密码" prop="oldPassword">
      <el-input type="password" v-model="form.oldPassword"></el-input>
    </el-form-item>
    <el-form-item label="新密码" required prop="newPassword">
      <el-input type="password" v-model="form.newPassword"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" required prop="againPassword">
      <el-input type="password" v-model="form.againPassword"></el-input>
    </el-form-item>
    <el-divider></el-divider>
    <div class="tr">
      <el-button @click="resetForm('passwordForm')">取消</el-button>
      <el-button type="primary" :loading="submiting" @click="onSubmit('passwordForm')">保存</el-button>
    </div>
  </el-form>
</template>

<script>
import md5 from "js-md5";
import { userPassword } from "api/user";
export default {
  data() {
    var validNewPass = (rule, value, callback) => {
      let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else {
        if (!value.match(reg)) {
          callback(new Error("密码必须包含字母和数字,且在6~18位之间"));
        } else {
          if (this.form.againPassword !== "") {
            this.$refs.passwordForm.validateField("againPassword");
          }
          callback();
        }
      }
    };
    var validAgainPass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入新密码"));
      } else if (value !== this.form.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      form: {
        oldPassword: "",
        newPassword: "",
        againPassword: ""
      },
      submiting: false,
      rules: {
        oldPassword: [
          { required: true, message: "请输入旧密码", trigger: "blur" }
        ],
        newPassword: [{ validator: validNewPass, trigger: "blur" }],
        againPassword: [{ validator: validAgainPass, trigger: "blur" }]
      }
    };
  },
  methods: {
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.submiting) return;
          this.submiting = true;
          userPassword({
            oldPassword: md5(this.form.oldPassword),
            newPassword: md5(this.form.newPassword)
          })
            .then(res => {
              this.submiting = false;
              this.$alert("密码修改成功！请退出重新登录~", "温馨提示", {
                confirmButtonText: "退出登录",
                type: "success",
                callback: action => {
                  this.logout();
                }
              });
            })
            .catch(err => {
              this.$message.error(err.msg);
              this.submiting = false;
            });
        } else {
          console.log("validate error");
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    async logout() {
      await this.$store.dispatch("user/logout");
      this.$router.push(`/login?redirect=${this.$route.fullPath}`);
    }
  }
};
</script>
